package com.hua.nailcampus.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hua.nailcampus.acl.mapper.*;
import com.hua.nailcampus.acl.model.*;
import com.hua.nailcampus.acl.model.vo.UserLoginVo;
import com.hua.nailcampus.acl.model.vo.UserVo;
import com.hua.nailcampus.acl.service.UserService;
import com.hua.nailcampus.utils.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:chenjianhua
 * @Date:2023/11/15 19:41
 * @Version 17
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AvatarMapper avatarMapper;

    @Autowired
    private UserCityMapper userCityMapper;

    @Autowired
    private ProvinceMapper provinceMapper;

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private UserSchoolMapper userSchoolMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private FriendsMapper friendsMapper;

    @Override
    public UserVo getUser(Integer id) {
//        根据id获取用户信息
        User user = userMapper.selectById(id);
//        将实体类赋值到数据类中
        UserVo userVo = new UserVo(user);
//        设置头像地址
        Avatar avatar = avatarMapper.selectById(id);
        if(avatar != null){
            userVo.setAvaUrl(avatar.getUrl());
        }
//        返回数据类
        return userVo;
    }

    @Override
    public UserVo loginUserByPassword(UserLoginVo userLoginVo) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().
                eq(User::getPhone, userLoginVo.getPhone()));
        // 用户不存在
        if(user == null){
            return null;
        }
        UserVo userVo = new UserVo(user);
//        查询该用户头像
        Avatar avatar = avatarMapper.selectOne(
                new LambdaQueryWrapper<Avatar>()
                        .eq(Avatar::getUserId,userVo.getId()));
        if(avatar != null){
            userVo.setAvaUrl(avatar.getUrl());
        }
//        判断密码是否正确
        String getPassword = MD5.encrypt(userLoginVo.getPassword());
        String dbPassword = user.getPassword();
        //密码错误
        if(!getPassword.equals(dbPassword)){
            return null;
        }
        UserCity userCity = userCityMapper.selectOne(new LambdaQueryWrapper<UserCity>()
                .eq(UserCity::getUserId, userVo.getId()));
        //是否设置了地址
        if(userCity!=null){
            City city = cityMapper.selectById(userCity.getCityId());
            userVo.setCityId(city.getId());
            userVo.setCityName(city.getName());
            userVo.setProvinceName(provinceMapper.selectById(city.getPId()).getName());
        }
        //是否认证了学校

        return userVo;
    }

    @Override
    public UserVo getUserByPhone(String phone) {
//        根据手机号查询用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, phone));
        if(user == null ){
            return null;
        }
        UserVo userVo = new UserVo(user);
        Avatar avatar = avatarMapper.selectOne(
                new LambdaQueryWrapper<Avatar>()
                        .eq(Avatar::getUserId, userVo.getId()));
        if (avatar != null){
            userVo.setAvaUrl(avatar.getUrl());
        }
        return userVo;
    }

    @Override
    public void updateUser(UserVo userVo) {
//        将用户数据类赋值到实体类
        User user = new User(userVo);
        //        查询以前是否存储过，若存储过则删除，若没有存储过则直接存储
        Avatar avatar = avatarMapper.selectOne(
                new LambdaQueryWrapper<Avatar>()
                        .eq(Avatar::getUserId, user.getId()));
        if(avatar != null) {
            // 把之前的头像实体类删除
            avatarMapper.delete(
                    new LambdaQueryWrapper<Avatar>()
                            .eq(Avatar::getUserId,user.getId()));
        }
//        重新获取头像实体类并设值
        avatar = new Avatar();
        avatar.setUserId(user.getId());
        avatar.setUrl(userVo.getAvaUrl());
//        将头像实体类存入数据库
        avatarMapper.insert(avatar);
//        用户实体类存入数据库
        userMapper.updateById(user);
//        更新地址
        UserCity userCity = userCityMapper.selectOne(new LambdaQueryWrapper<UserCity>()
                .eq(UserCity::getUserId, user.getId()));
        if(userCity!=null){
            userCity.setCityId(userVo.getCityId());
        }
        userCityMapper.updateById(userCity);
    }

    @Override
    public UserVo getUserById(Integer userId,Integer id) {
//        根据ID获取用户实体类
        User user = userMapper.selectById(id);
//        初始化UserVo类
        UserVo userVo = new UserVo(user); 
//        根据用户ID获取头像地址
        Avatar avatar = avatarMapper.selectOne(
                new LambdaQueryWrapper<Avatar>()
                        .eq(Avatar::getUserId, user.getId()));
//        不为空则代表该用户有头像地址，设置到UserVo中
        if( avatar != null){
            userVo.setAvaUrl(avatar.getUrl());
        }
        String schoolName = userSchoolMapper.selectUserSchoolName(id);
        if(schoolName!=null){
            userVo.setSchoolName(schoolName);
        }
        if(userId!=null){
            Friends friends = friendsMapper.selectOne(new LambdaQueryWrapper<Friends>()
                    .eq(Friends::getUId, userId)
                    .eq(Friends::getFId,id));
            if(friends!=null){
                if(friends.getFName()!=null){
                    userVo.setUserName(friends.getFName());
                }
            }
        }
//        返回UserVo
        return userVo;
    }

    @Override
    public void logout(Integer userId) {
        User user = userMapper.selectById(userId);
        user.setStatus(false);
        userMapper.updateById(user);
    }

    @Override
    public  IPage<UserVo> getAllUser(Integer current,Integer limit,User userParam) {
        String userName = userParam.getUserName();
        String phone = userParam.getPhone();
        Integer id = userParam.getId();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if(userName !=null){
           wrapper.like(User::getUserName,userName);
        }
        if(phone != null){
            wrapper.like(User::getPhone,phone);
        }
        if(id!=null){
            wrapper.like(User::getId,id);
        }
        IPage<UserVo> userVoPage = new Page<>(current, limit);
        List<User> userList = userMapper.selectList(wrapper);
        List<UserVo> userVoList = new ArrayList<>();
        for (User user : userList){
            UserVo userVo = new UserVo(user);
//            查询头像
            Avatar avatar = avatarMapper.selectOne(new LambdaQueryWrapper<Avatar>().eq(Avatar::getUserId, user.getId()));
            if(avatar!=null){
                userVo.setAvaUrl(avatar.getUrl());
            }
//            查询学校名称
            UserSchool userSchool = userSchoolMapper.selectOne(new LambdaQueryWrapper<UserSchool>()
                    .eq(UserSchool::getUserId, user.getId())
                    .eq(UserSchool::getStatus,true));
            if(userSchool!=null){
                String schoolName = userSchoolMapper.selectUserSchoolName(user.getId());
                userVo.setSchoolName(schoolName);
                userVo.setStudentId(userSchool.getStudentId());
            }
            Role role = roleMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getUserId, user.getId()));
            userVo.setRoleId(role.getCode());
            userVoList.add(userVo);
        }
        userVoPage.setRecords(userVoList);
        return userVoPage;
    }

    @Override
    public Integer getUserRole(Integer userId) {
        Role role = roleMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getUserId, userId));
        return role.getCode();
    }

    @Override
    public void UpdateRole(UserVo userVo) {
        Role role = roleMapper.selectOne(new LambdaQueryWrapper<Role>()
                .eq(Role::getUserId, userVo.getId()));
        role.setCode(userVo.getRoleId());
        roleMapper.updateById(role);
    }

    @Override
    public void createRole(User user) {
        User user1 = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, user.getPhone()));
        Role role = new Role();
        role.setUserId(user1.getId());
        role.setCode(0);
        roleMapper.insert(role);
    }

}
